package com.excellence.controller;

import com.alibaba.fastjson.JSON;
import com.excellence.datamodel.Result;
import okhttp3.*;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;

/**
 * @author 沈秉璋
 * @ClassName PictureRecognitionController
 * @Description TODO
 * @date 2024/4/28 20:38
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/pictureRecognition")
public class PictureRecognitionController {
    public static final String API_KEY = "hFWcxSdJMQVihaIaLLehdjwh";
    public static final String SECRET_KEY = "orc6LIKv0Wb5v5CG0DaXxoY4OydNwsXw";
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    static final String ACCESS_TOKEN = "24.cd52259ecf877850b0ef46f746b499e4.2592000.1716902063.282335-60158757";

    @PostMapping("/getPictureRecognition")
    public Result getPictureRecognition(String type, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        String image = getFileContentAsBase64(file, true);

        RequestBody body = RequestBody.create(mediaType, "image=" + image);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v1/" + type + "?access_token=" + ACCESS_TOKEN)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSON res = (JSON) JSON.parse(response.body().string());
        System.out.println(res);
        return Result.success(res);
    }

    /**
     * 获取文件base64编码
     *
     * @param file      为MultipartFile类型的文件
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */

    public static String getFileContentAsBase64(MultipartFile file, boolean urlEncode) throws IOException {
        byte[] b = file.getBytes();
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}
